<template>
  <div>
    <el-input v-model="url" type="text" style="width: 100%" /> &nbsp; &nbsp;
    <br />
    <el-button @click="join" type="primary">连接</el-button>
    <el-button @click="exit" type="danger">断开</el-button>

    <br />
    <el-input type="textarea" v-model="message" :rows="9" />
    <el-button type="primary" @click="send">发送消息</el-button>
    <br />
    <br />
    <el-input type="textarea" v-model="text_content" :rows="9" /> 返回内容
    <br />
    <br />
  </div>
</template>

<script setup>
import { getToken } from '@/utils/auth';

  //url: "ws://127.0.0.1:9060/websocket/admin"+ "?Authorization=Bearer " + getToken() + "&clientid=" + import.meta.env.VITE_APP_CLIENT_ID,
  const url = ref("ws://127.0.0.1:9060/websocket/admin")
  const message = ref("")
  const text_content = ref("")
  let ws = null

  const join = () => {
    const wsuri = url.value;
    ws = new WebSocket(wsuri);
    ws.onopen = function (event) {
      text_content.value = text_content.value + "已经打开连接!" + "\n";
    };
    ws.onmessage = function (event) {
      text_content.value = event.data + "\n";
    };
    ws.onclose = function (event) {
      text_content.value = text_content.value + "已经关闭连接!" + "\n";
    };
  }
  const exit = () => {
    if (ws) {
      ws.close();
      ws = null;
    }
  }
  const send = () => {
    if (ws) {
      const messageData = {
        msgTxt: message.value,
        cmd: 'user'
      }
      let strdata = JSON.stringify(messageData);
       console.log("strdata",JSON.stringify(messageData));
      ws.send(strdata);
      //ws.send(message.value);
    } else {
      alert("未连接到服务器");
    }
  }

</script>
